package com.tticar.invmanager.tticar.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.czy.tticar.model.GoodsWithBLOBs;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.shiro.MySecurityUtils;
import com.tticar.invmanager.common.utils.PinYinUtil;
import com.tticar.invmanager.common.utils.StringTticarUtils;
import com.tticar.invmanager.entity.MMateriel;
import com.tticar.invmanager.entity.MMaterielSku;
import com.tticar.invmanager.entity.MMaterielTticar;
import com.tticar.invmanager.entity.SysPictrue;
import com.tticar.invmanager.entity.vo.GoodsSearchDTO;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.SkuReturnToPage;
import com.tticar.invmanager.entity.vo.TticarGoodsSkusDTO;
import com.tticar.invmanager.mapper.MMaterielSkuMapper;
import com.tticar.invmanager.mapper.MMaterielTticarMapper;
import com.tticar.invmanager.service.IMMaterielService;
import com.tticar.invmanager.service.IMMaterielSkuService;
import com.tticar.invmanager.service.IMMaterielTticarService;
import com.tticar.invmanager.service.ISysPictrueService;
import com.tticar.invmanager.tticar.entity.Goods;
import com.tticar.invmanager.tticar.entity.GoodsProduction;
import com.tticar.invmanager.tticar.entity.GoodsTmp;
import com.tticar.invmanager.tticar.entity.Pictures;
import com.tticar.invmanager.tticar.mapper.GoodsMapper;
import com.tticar.invmanager.tticar.service.IGoodsProductionService;
import com.tticar.invmanager.tticar.service.IGoodsService;
import com.tticar.invmanager.tticar.service.IPicturesService;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 产品表 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-18
 */
@Service
@Transactional
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private IMMaterielTticarService materielTticarService;
    @Autowired
    private IGoodsProductionService goodsProductionService;
    @Autowired
    private ISysPictrueService sysPictrueService;
    @Autowired
    private IPicturesService picturesService;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MMaterielTticarMapper mMaterielTticarMapper;
    @Autowired
    private IMMaterielSkuService mMaterielSkuService;
    @Autowired
    private MMaterielSkuMapper mskuMapper;
    @Autowired
    private IMMaterielService materielService;
    @Autowired
    private MMaterielTticarMapper mmapper;

    @Override
    public List<Map> category(Wrapper w) {
        return baseMapper.category(w);
    }

    @Override
    public List<Map> synchronizationCategory() {
        return baseMapper.synchronizationCategory();
    }

    @Override
    public List<Map> brand(MyPage page, Wrapper w) {
//        List<Long> longs = mmapper.queryTticarStoreListByTenantId();

        return baseMapper.brand(page, w);
    }

    @Override
    public Map getById(Long id) {
        //根据id查出 仓储id
//        Map<String, Object> map = materielTticarService.selectMap(Condition.create().eq(MMaterielTticar.ID, id));

//        Long goodsId = MapUtils.getLong(map, "ttgoodsId");
        Map _map = this.selectMap(Condition.create().eq(Goods.ID, id));
//        for (String key : map.keySet()) {
//            _map.put(key, map.get(key));
//        }
        _map.put("skus", goodsProductionService.selectList(Condition.create().eq(GoodsProduction.GOODID, id)));
        _map.put("ttgoodsId", id.toString());
        _map.put("ttstoreId", _map.get("storeId"));
        Wrapper w = Condition.create();
        w.eq("id", _map.get("categoryId"));
        List<Map> category = this.category(w);
        _map.put("catgoryName",category.get(0).get("name"));

        //查出轮播图
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("refId", id);
        String picIds = "";
        List<Pictures> pictures = picturesService.selectList(wrapper);
        if (pictures != null && pictures.size() > 0) {
            for (Pictures pic : pictures) {
                picIds = picIds + pic.getId() + ",";
            }
        }
        if (StringUtils.isNotBlank(picIds)) {
            picIds = picIds.substring(0, picIds.length() - 1);
            _map.put("pictures", picIds);
        }
        return _map;
    }

    @Override
    @Transactional(value = "ttTransactionManager")
    public void insert(MMaterielTticar mMaterielTticar, Goods goods, List<GoodsProduction> goodsProductions,Long materielId) {
        Date date = new Date();
        // 新增产品
        String s = goods.getStandardCfg();
        if (s.contains("goodsIdString")) {

            String s1 = s.substring(0, s.indexOf("goodsIdString")-1);
            String s2 = s.substring(s.indexOf("goodsIdString"), s.length());
            String s3 = s2.substring(s2.indexOf(",")+1, s2.length());
            s = s1+s3;
            if (s3.contains("isRelative")) {
                String s4 = s.substring(0, s.indexOf("isRelative")-1);
                String s5 = s.substring(s.indexOf("isRelative"), s.length());
                String s6 = s5.substring(s5.indexOf(",")+1, s5.length());
                s = s4 + s6;
            }
        }
        goods.setStandardCfg(s);
        goods.setId(mMaterielTticar.getTtgoodsId());
        goods.setNameSpell(PinYinUtil.getFirstLetter(goods.getName()));
        goods.setCreatetime(date);
        goods.setUptime(date);
        goods.setModifytime(date);
        goods.setStoreId(mMaterielTticar.getTtstoreId());
        //生成商品唯一码
        Long categoryNo = goodsMapper.queryCategoryNo(goods.getCategoryId());
        final char padChar = '0';
        final String categoryPart = StringTticarUtils.leftPad(String.valueOf(categoryNo), 2, padChar);
        String goodNoPart;
        GoodsWithBLOBs good = new GoodsWithBLOBs();
        goodsMapper.insertGoodno(good);
        goodNoPart = StringTticarUtils.leftPad(good.getGoodno(), 6, padChar);
        String goodsNo = StringTticarUtils.join(categoryPart, goodNoPart);
        goods.setGoodNo(goodsNo);
        //插入goods_extend
        this.insertOrUpdate(goods);
        Long aLong1 = goodsMapper.queryGoodsExtend(goods.getId());
        if (aLong1 == null) {
            goodsMapper.insertGoodsExtend(goods.getId());
        }

        //插入价格表
        Long aLong = goodsMapper.queryGoodsPriceId(goods.getId());
        Map map1 = new HashMap<>(8);
        map1.put("goodsId", goods.getId());
        map1.put("price", goods.getPricemember());
        map1.put("vip", goods.getPricemember());
        map1.put("vip2", goods.getPricemember());
        map1.put("vip3", goods.getPricemember());
//        map1.put("vip",goods.get)
        if (aLong == null) {
            goodsMapper.insertGoodsPrice(map1);
        }else {
            goodsMapper.updateGoodsPrice(map1);
        }


        // 规格
        if (goods.getId() != null) {
            goodsProductionService.delete(Condition.create().eq(GoodsProduction.GOODID, goods.getId()));
        }
        List<Long> skuIds = new ArrayList<>();
        for (int i = 0; i < goodsProductions.size(); i++) {
            GoodsProduction goodsProduction = goodsProductions.get(i);
            goodsProduction.setGoodId(goods.getId());
            skuIds.add(goodsProduction.getId());
            goodsProduction.setSkuId((i + 1) + "");
            goodsProduction.setId(null);
            goodsProduction.setCreatetime(date);
            goodsProduction.setModifytime(date);
            //不存在活动价
            goodsProduction.setPrice(null);
        }
        if (goodsProductions == null || goodsProductions.size() < 1) {
            throw new MyServiceException("规格信息不能为空");
        }
        goodsProductionService.insertBatch(goodsProductions);
        //图片
        if (StringUtils.isNotEmpty(mMaterielTticar.getPictrues())) {
            List<Map<String, Object>> pics = sysPictrueService.getByIds(mMaterielTticar.getPictrues());
            if (!pics.isEmpty()) {
                picturesService.delete(Condition.create().eq(Pictures.REFID, goods.getId()).eq(Pictures.TYPE, 1));
                List<Pictures> list = new ArrayList();
                for (int i = 0; i < pics.size(); i++) {
                    Map map = pics.get(i);
                    Pictures pictures = new Pictures();
                    pictures.setRefId(goods.getId());
                    pictures.setPath(MapUtils.getString(map, SysPictrue.PATH));
                    pictures.setSort(i + 10);
                    pictures.setIsportal(i == 0 ? 1 : 0);
                    pictures.setType(1);
                    list.add(pictures);
                }
                picturesService.insertBatch(list);
            }
        }
        //
        mMaterielTticar.setMaterielSkuIds(skuIds.toString().replace("[", "").replace("]", ""));
        mMaterielTticar.setTtgoodsId(goods.getId());
//        materielTticarService.insertOrUpdate(mMaterielTticar);无用

        MMateriel materiel = new MMateriel();
        materiel.setId(materielId);
        materiel.setTticarGoodsId(1L);
        materielService.updateById(materiel);
        //进行关联
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("mid", materielId);
        List<MMaterielSku> mMaterielSkus1 = mMaterielSkuService.selectList(wrapper1);
        List<SkuReturnToPage> skuValuesByGoodsId = goodsMapper.getSkuValuesByGoodsId(goods.getId());
        for (int i = 0; i < skuValuesByGoodsId.size(); i++) {
            for (int j = 0; j<mMaterielSkus1.size();j++ ) {
                if (mMaterielSkus1.get(j).getSkus().equals(skuValuesByGoodsId.get(i).getSkuName())) {
                    Long tenantId = MySecurityUtils.currentUser().getTenantId();
                    mskuMapper.insertRelativeTticarGoodsAndInvSku(goods.getId().toString(), skuValuesByGoodsId.get(i).getSkuValue(), mMaterielSkus1.get(j).getId(),tenantId);
                }
            }
        }
    }

    @Override
    public Page selectPage(MyPage<GoodsTmp> page, GoodsSearchDTO goodsSearchDTO) {
        Map map = new HashMap<>(4);
        if (goodsSearchDTO != null) {
            map.put("storeIdList", goodsSearchDTO.getSellStoreIdList());
            map.put("name", goodsSearchDTO.getName());
            map.put("code", goodsSearchDTO.getCode());
            map.put("onLineStatus", goodsSearchDTO.getOnlineStatus());
            String goodsIdListString;
            if (goodsSearchDTO.getRelativeStatus() != null && goodsSearchDTO.getRelativeStatus() == 1) {
                List<Long> goodsIdList = mMaterielTticarMapper.queryGoodsHasRelativeList(MySecurityUtils.currentUser().getTenantId());
                if (goodsIdList != null && goodsIdList.size() > 0) {
                    goodsIdListString = "(1,";
                    for (int i = 0; i < goodsIdList.size(); i++) {
                        goodsIdListString = goodsIdListString + goodsIdList.get(i) + ",";
                    }
                    goodsIdListString = goodsIdListString.substring(0, goodsIdListString.length() - 1);
                    goodsIdListString = goodsIdListString + ")";
                    map.put("goodsIdListString", goodsIdListString);
                } else {
                    return page.setRecords(null);
                }
            } else if (goodsSearchDTO.getRelativeStatus() != null && goodsSearchDTO.getRelativeStatus() == 2) {
                List<Long> goodsIdList = mMaterielTticarMapper.queryGoodsHasRelativeList(MySecurityUtils.currentUser().getTenantId());
                if (goodsIdList != null && goodsIdList.size() > 0) {
                    goodsIdListString = "(1,";
                    for (int i = 0; i < goodsIdList.size(); i++) {
                        goodsIdListString = goodsIdListString + goodsIdList.get(i) + ",";
                    }
                    goodsIdListString = goodsIdListString.substring(0, goodsIdListString.length() - 1);
                    goodsIdListString = goodsIdListString + ")";
                    map.put("notInList", goodsIdListString);
                }
            }
        }

        List<GoodsTmp> goodsTmps = goodsMapper.queryTticarGoodsList(page, map);
        //关联过的商品
        List<Long> goodsIdList = mMaterielTticarMapper.queryGoodsHasRelativeList(MySecurityUtils.currentUser().getTenantId());
        if (goodsIdList != null && goodsIdList.size() > 0) {
            for (GoodsTmp goodsTmp : goodsTmps) {
                Long id = Long.valueOf(goodsTmp.getId());
                if (goodsIdList.contains(id)) {
                    goodsTmp.setRelativeStatus(1);
                } else {
                    goodsTmp.setRelativeStatus(0);
                }
            }
        } else {
            for (GoodsTmp goodsTmp : goodsTmps) {
                    goodsTmp.setRelativeStatus(0);
            }
        }

        return page.setRecords(goodsTmps);
    }

    @Override
    public List<SkuReturnToPage> querySkusByGoodsId(Long goodsId) {
        return goodsMapper.querySkusByGoodsId(goodsId);
    }

    @Override
    public Object queryById(Long id) {
        Map map = this.selectMap(Condition.create().eq("id", id));
        List<TticarGoodsSkusDTO> tticarGoodsSkus = goodsMapper.tticarGoodsSkus(id);

        for (int i = 0; i < tticarGoodsSkus.size(); i++) {
            Map map1 = new HashMap<>(8);
            map1.put("0", tticarGoodsSkus.get(i).getVip0() == null ? "0.00" : tticarGoodsSkus.get(i).getVip0());
            map1.put("1", tticarGoodsSkus.get(i).getVip1() == null ? "0.00" : tticarGoodsSkus.get(i).getVip1());
            map1.put("2", tticarGoodsSkus.get(i).getVip2() == null ? "0.00" : tticarGoodsSkus.get(i).getVip2());
            map1.put("3", tticarGoodsSkus.get(i).getVip3() == null ? "0.00" : tticarGoodsSkus.get(i).getVip3());
            String jsonString = JSON.toJSONString(map1);
            tticarGoodsSkus.get(i).setPrices(jsonString);
        }
        map.put("mSkus", tticarGoodsSkus);
        map.put("categoryId", null);
        return map;
    }
}
